﻿/*
-----------------------------------------------------------------------------
This source file is part of Cell Cloud.

Copyright (c) 2009-2012 Cell Cloud Team - cellcloudproject@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "CellStableHeaders.h"
#include "CellConfig.h"
#include "CellCrashReport.h"
#include "CellLoggerManager.h"
#include "CellNucleus.h"

#ifdef CELL_CRASH_REPORT

#if CELL_PLATFORM == CELL_PLATFORM_WIN32

#include "CrashRpt.h"
#pragma comment(lib, "CrashRpt1300.lib")
#pragma comment(lib, "version.lib")

namespace cell
{

BOOL WINAPI CrashCallback(LPVOID /*lpvState*/);

template<> CrashReport* Singleton<CrashReport>::ms_Singleton = NULL;

//-----------------------------------------------------------------------
CrashReport* CrashReport::getSingletonPtr(void)
{
	return ms_Singleton;
}
//-----------------------------------------------------------------------
CrashReport& CrashReport::getSingleton(void)
{
	assert( ms_Singleton );  return ( *ms_Singleton );  
}

//-----------------------------------------------------------------------
CrashReport::CrashReport(void) : mAvailable(false)
{
}
//-----------------------------------------------------------------------
CrashReport::~CrashReport(void)
{
}
//-----------------------------------------------------------------------
void CrashReport::install(void)
{
	MINIDUMP_TYPE MiniDumpWithDataSegs = static_cast<MINIDUMP_TYPE>(MiniDumpNormal
		| MiniDumpWithHandleData
		| MiniDumpWithUnloadedModules
		| MiniDumpWithIndirectlyReferencedMemory
		| MiniDumpScanMemory
		| MiniDumpWithProcessThreadData
		| MiniDumpWithThreadInfo);

	char saveDir[64] = {0x0};
	generateErrorReportSaveDir(saveDir, 64);

	CR_INSTALL_INFO info;
	memset(&info, 0, sizeof(CR_INSTALL_INFO));
	info.cb = sizeof(CR_INSTALL_INFO);
	info.pszAppName = "Cell Cloud";
	info.pszAppVersion = "0.1.1";
	info.pszEmailSubject = "Cell Cloud 0.1.1 Error Report";
	info.pszEmailTo = "cellcloudproject@gmail.com";
	info.pszUrl = "http://www.cellcloud.net/crashrpt.php";
	info.pfnCrashCallback = CrashCallback;
	info.uPriorities[CR_HTTP] = 3;  // First try send report over HTTP
	info.uPriorities[CR_SMTP] = 2;  // Second try send report over SMTP
	info.uPriorities[CR_SMAPI] = 1; // Third try send report over Simple MAPI    
	// Install all available exception handlers.
	info.dwFlags |= CR_INST_ALL_POSSIBLE_HANDLERS;
	info.dwFlags |= CR_INST_CRT_EXCEPTION_HANDLERS;
	//info.dwFlags |= CR_INST_APP_RESTART;
	//info.dwFlags |= CR_INST_SEND_QUEUED_REPORTS;
	info.dwFlags |= CR_INST_DONT_SEND_REPORT;
	info.uMiniDumpType = MiniDumpWithDataSegs;
	info.pszErrorReportSaveDir = saveDir;
	//info.pszRestartCmdLine = "/restart";
	info.pszPrivacyPolicyURL = "http://www.cellcloud.net/privacypolicy.html";

	int nResult = crInstall(&info);
	if (nResult != 0)
	{
		// Something goes wrong. Get error message.
		TCHAR szErrorMsg[512] = {0x0};
		crGetLastErrorMsg(szErrorMsg, 512);
		sprintf("%s", szErrorMsg);
		LoggerManager::getSingleton().log(szErrorMsg);
		mAvailable = false;
	}
	else
	{
		// Add cell cloud log file to the error report
		if (LoggerManager::getSingletonPtr() != NULL)
			crAddFile2(LoggerManager::getSingletonPtr()->getDefaultLogger()->getName().c_str(),
				NULL, "Log File", CR_AF_MAKE_FILE_COPY);

		// Add nucleus tag
		if (Nucleus::getSingletonPtr() != NULL)
			crAddProperty("Nucleus Tag", Nucleus::getSingletonPtr()->getTagAsString().c_str());
		mAvailable = true;
	}
}
//-----------------------------------------------------------------------
void CrashReport::uninstall(void)
{
	if (mAvailable)
	{
		crUninstall();
	}
}
//-----------------------------------------------------------------------
void CrashReport::installToCurrentThread(void)
{
	if (NULL != CrashReport::getSingletonPtr() && CrashReport::getSingletonPtr()->mAvailable)
	{
		// Install exception handlers
		crInstallToCurrentThread2(0);
	}
}
//-----------------------------------------------------------------------
void CrashReport::uninstallFromCurrentThread(void)
{
	if (NULL != CrashReport::getSingletonPtr() && CrashReport::getSingletonPtr()->mAvailable)
	{
		// Uninstall exception handlers
		crUninstallFromCurrentThread();
	}
}
//-----------------------------------------------------------------------
void CrashReport::generateErrorReportSaveDir(char* dirBuff, int bufSize)
{
	::CreateDirectory("CrashReport", NULL);

	char buf[128] = {0x0};
	SYSTEMTIME st;
	::GetLocalTime(&st);
	wsprintf(buf, TEXT(".\\CrashReport\\%04d-%02d-%02d-%02d-%02d-%02d-%03d"), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
	memcpy(dirBuff, buf, strlen(buf));

	// 删除空目录
	namespace bfs = boost::filesystem;
	bfs::path p("CrashReport");
	bfs::directory_iterator diter(p), dend;
	while (diter != dend)
	{
		if (bfs::is_directory(*diter) && bfs::is_empty(*diter))
		{
			bfs::remove(*diter);
		}

		++diter;
	}
}
//-----------------------------------------------------------------------
bool CrashReport::checkCrashRptVersion(void)
{
	bool bExitCode = false;
	TCHAR szModuleName[_MAX_PATH] = "";
	HMODULE hModule = NULL;
	DWORD dwBuffSize = 0;
	LPBYTE pBuff = NULL;
	VS_FIXEDFILEINFO* fi = NULL;
	UINT uLen = 0;

	// Get handle to loaded CrashRpt.dll module
	hModule = GetModuleHandle("CrashRpt.dll");
	if (hModule == NULL)
		goto cleanup; // No "CrashRpt.dll" module loaded

	// Get module file name
	GetModuleFileName(hModule, szModuleName, _MAX_PATH);

	// Get module version 
	dwBuffSize = GetFileVersionInfoSize(szModuleName, 0);
	if (dwBuffSize == 0)
		goto cleanup; // Invalid buffer size

	pBuff = (LPBYTE)GlobalAlloc(GPTR, dwBuffSize);
	if (pBuff == NULL)
		goto cleanup;

	if (0 == GetFileVersionInfo(szModuleName, 0, dwBuffSize, pBuff))
		goto cleanup; // No version info found

	VerQueryValue(pBuff, ("\\"), (LPVOID*)&fi, &uLen);

	WORD dwVerMajor = HIWORD(fi->dwProductVersionMS);
	WORD dwVerMinor = LOWORD(fi->dwProductVersionMS);  
	WORD dwVerBuild = LOWORD(fi->dwProductVersionLS);

	DWORD dwModuleVersion = dwVerMajor*1000+dwVerMinor*100+dwVerBuild;

	if (CRASHRPT_VER == dwModuleVersion)
		bExitCode = true; // Version match!

cleanup:

	if (pBuff)
	{
		// Free buffer
		GlobalFree((HGLOBAL)pBuff);
		pBuff = NULL;
	}

	return bExitCode;
}


BOOL WINAPI CrashCallback(LPVOID /*lpvState*/)
{
	// The application has crashed!
	// Return TRUE to generate error report
	return TRUE;
}

} // end namespace cell

#endif // CELL_PLATFORM == CELL_PLATFORM_WIN32

#endif // CELL_CRASH_REPORT
